package ginv

import (
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

// DefaultMiddlewares 默认中间件配置
func (ch *ChainHandler) DefaultMiddlewares() *ChainHandler {
	return ch.Use(
		gin.Logger(),
		gin.Recovery(),
		CORSMiddleware(),
	)
}

// CORSMiddleware CORS中间件
func CORSMiddleware() gin.HandlerFunc {
	return cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"*"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	})
}

// RequestIDMiddleware 请求ID中间件
func RequestIDMiddleware() gin.HandlerFunc {
	return gin.HandlerFunc(func(c *gin.Context) {
		requestID := c.GetHeader("X-Request-ID")
		if requestID == "" {
			requestID = generateRequestID()
		}
		c.Header("X-Request-ID", requestID)
		c.Set("request_id", requestID)
		c.Next()
	})
}

// generateRequestID 生成请求ID
func generateRequestID() string {
	// 简单的时间戳ID生成
	return time.Now().Format("20060102150405") + "000"
}

// AuthMiddleware 认证中间件示例
func AuthMiddleware() gin.HandlerFunc {
	return gin.HandlerFunc(func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token == "" {
			c.JSON(401, gin.H{
				"ret": 1,
				"msg": "未授权访问",
			})
			c.Abort()
			return
		}
		// 这里可以添加token验证逻辑
		c.Next()
	})
}

// RateLimitMiddleware 限流中间件示例
func RateLimitMiddleware(maxRequests int, duration time.Duration) gin.HandlerFunc {
	// 这里可以实现基于内存或Redis的限流逻辑
	return gin.HandlerFunc(func(c *gin.Context) {
		// 简单示例，实际使用时需要实现真正的限流逻辑
		c.Next()
	})
}